<template>
    <SelectActEquip v-if="selectEquipVisible" @confirm="selectConfirm" @cancel="selectEquipVisible = false"></SelectActEquip>
    <div class="e-form" v-else>
        <div class="tabs" v-if="Object.keys(formData).length != 0">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                 <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                            <div style="width: 100%" class="form">
                                <el-form ref="form" :model="formData" label-width="200px">
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="设备编号：">
                                                <span>{{ formData.equipmentNo }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="外协单位：">
                                                <span>{{ formData.supplierName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="设备名称：">
                                                <span>{{ formData.equipmentName }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="规格型号：">
                                                <span>{{ formData.specificationModel }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="计量单位：">
                                                <span>{{ formData.unit }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="操作手：">
                                                <span>{{ formData.operatorName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="进场时间：">
                                                <span>{{ formData.enterDate }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="退场时间：">
                                                <span>{{ formData.exitDate }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                    <el-col :span="12">
                                            <el-form-item label="使用地点：">
                                                <span>{{ formData.useSite }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="外协设备来源：">
                                                <span>{{ equipmentSource.find(x=>x.value === formData.equipmentSource).label }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                    <el-col :span="12">
                                            <el-form-item label="出租/销售单位：">
                                                <span>{{ formData.leaseSaleUnit }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="已付租赁/设备费（元）：">
                                                <span>{{ formData.paid }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                    <el-col :span="12">
                                            <el-form-item label="车牌编号：">
                                                <span>{{ formData.plateNo }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="未付租赁/设备费（元）：">
                                                <span>{{ formData.unpaid }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="12">
                                            <el-form-item label="进退场状态：">
                                                <span>{{ enterExitStatus.find(x=>x.value === formData.enterExitStatus).label }}</span>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="所属机构：">
                                                <span>{{ formData.orgName }}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                            </div>
                    </div>
                </div>
            </el-tabs>
        </div>
         <div class="buttons">
                <el-button type="primary" size="small" class="btn-blue"
                    >打印二维码</el-button
                >
                <el-button size="small" @click="handleClose">取消</el-button>
            </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/equipAccount.js'
import '@/utils/jquery.scrollTo.min'
import SelectActEquip from '@/pages/equipment/equipPlan/majorPlan/majorPlanAddDialog/maintenancePlan.vue'
import { formatDate } from '@/utils/common.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            selectEquipVisible: false,
            tableData: [],
            formData: {
                'categoryId': '',
                'categoryName': '',
                'enrollDate': '',
                'enterDate': '',
                'enterExitStatus': 0,
                'equipmentCondition': 0,
                'equipmentId': '',
                'equipmentName': '',
                'equipmentNo': '',
                'equipmentSource': 0,
                'exitDate': '',
                'leaseAccountId': '',
                'leaseSaleUnit': '',
                'operatorName': '',
                'orgId': '',
                'orgName': '',
                'paid': 0,
                'plateNo': '',
                'specificationModel': '',
                'supplierId': '',
                'supplierName': '',
                'unit': 0,
                'unpaid': 0,
                'useSite': ''
            },
            billid: '',
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            equipmentSource: state=>state.equip.equipData.equipmentSource, //外协设备来源
            enterExitStatus: state=>state.equip.equipData.enterExitStatus, //进退场状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        SelectActEquip
    },
    created () {
        this.billid = this.$route.query.billid
        console.log('billid', this.billid)
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        this.getInfo()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        selectEquip () {
            this.selectEquipVisible = true
        },
        //获取基本信息
        getInfo () {
            const params = {
                id: this.billid,
            }
            request.outAccountBaseInfo(params).then(res=>{
                this.formData = res
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //选择设备确认
        selectConfirm (data) {
            if(!data) return false
            this.formData.handoverTransferDtlList = this.formData.handoverTransferDtlList ? this.formData.handoverTransferDtlList : []
            data.forEach(item=>{
                let obj = {
                    'acceptanceDtlId': '',
                    'accountId': '',
                    'billId': '',
                    'categoryId': '',
                    'categoryName': '',
                    'enterPrice': 0,
                    'equipmentId': '',
                    'equipmentName': '',
                    'equipmentNo': '',
                    'exitPrice': 0,
                    'handoverDate': '',
                    'isMaintancence': 0,
                    'leaseAmount': 0,
                    'leasePrice': 0,
                    'leaseTerm': 0,
                    'leaseUnit': '',
                    'maintainUnit': 0,
                    'maintenanceUnit': 0,
                    'manufacturer': '',
                    'oneLevelCategoryId': '',
                    'oneLevelCategoryName': '',
                    'operatingSalary': 0,
                    'originalNo': '',
                    'originalPlace': '',
                    'originalPlaceId': '',
                    'productionDate': '',
                    'productionNo': '',
                    'purchasePrice': 0,
                    'specificationModel': '',
                    'startTime': '',
                    'transferDtlId': '',
                    'transferId': '',
                    'unit': '',
                    ...item
                }
                let date  = formatDate(new Date(), 'yyyy-MM-dd')
                obj.startTime = date
                this.formData.handoverTransferDtlList.push(obj)
            })
            console.log('handoverTransferDtlList', this.formData.handoverTransferDtlList)
            this.selectEquipVisible = false
        },

        // 打开客户端弹窗，调用客户端api
        openApp () {
            window.getPopData = this.getPopData // 向客户端开放全局变量，让客户端在关闭弹窗时回调并传递回数据
            callbackObj.changeLoadingState(true) // ChangeLoadingState为客户端提供打开loading的方法

            // 本地模拟ajax异步，编写业务代码时修改为ajax
            setTimeout(() => {
                callbackObj.changeLoadingState(false) // 调用客户端api关闭loadin
                callbackObj.openWindow('/search') // OpenWindow为客户端提供打开弹窗的方法
            }, 2000)
        },
        // 接收客户端回调数据的方法
        getPopData (msg) {
            // 接收弹窗关闭时的form表单数据，并处理业务逻辑
            alert(`getPopData: ${msg}`)

            window.getPopData = null // 释放全局变量
        },
        //保存
        preserve () {
            request.outAccountUpdate(this.formData).then(()=>{
                this.clientPop('suc', '保存成功', ()=>{ this.$router.push('/outAccountList') })
            })
        },
        //删除
        deleteBIll () {
            this.clientPop('err', '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。', ()=>{
                request.outAccountDelete({ id: this.billid }).then(()=>{
                    this.clientPop('suc', '删除成功', ()=>{ this.$router.push('/outAccountList') })
                })
            })
        },
        //取消
        handleClose () {
            this.$router.go(-1)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
